const express = require("express");
const mongoose = require("mongoose");
const productDebugger = require("debug")("app:product");
const Response = require("../utils/response");

const productSchema = mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
  description: String,
});

const Product = mongoose.model("Product", productSchema);

async function createProduct(name, price, description) {
  const product = new Product({ name, price, description });
  const result = await product.save();
  return result;
}

router = express();

router.post("/add", async function (req, res) {
  const { name, price, description } = req.query;
  try {
    const data = await createProduct(name, price, description);
    const result = new Response(data);
    productDebugger(result);
    res.send(result);
  } catch (ex) {
    pruductDebugger("ERROR:", message);
  }
});

router.get("/get", async (req, res) => {
  const { name, _id } = req.query;
  if (_id) {
    const result = await Product.findById(_id);
    res.send(new Response(result));
    return;
  }
  if (name) {
    const result = await Product.find({ name });
    res.send(new Response(result));
    return;
  }
});

module.exports = router;
